//
//  WGQAlbumWithOutTitleTableViewCell.m
//  meiang_edu
//
//  Created by JUMIWGQ on 2018/10/1.
//  Copyright © 2018 com.meiang.meiang_edu. All rights reserved.
//

#import "WGQAlbumWithOutTitleTableViewCell.h"
#import "WGQAlbumCollectionViewCell.h"
#import "WGQTransfersRecordsAlertView.h"
#import "UIView+ShowView.h"
#import "WGQGrowUpLittleModel.h"

@interface WGQAlbumWithOutTitleTableViewCell ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong) UICollectionView * collectionView;
@property (nonatomic,strong) NSMutableArray * collectionArray;
@property (nonatomic,strong) NSIndexPath * indexPath;
@property (nonatomic,strong) UIView * backView;
@property (nonatomic,copy) NSString * photoAlbum_id;//相册id

@end

@implementation WGQAlbumWithOutTitleTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        self.collectionArray = [NSMutableArray array];
        self.contentView.backgroundColor = FFColor(0xebebeb);
        self.photoAlbum_id = @"474700ad-5c31-4df7-ab74-fe7b392cec41";
        [self addSubViews];
    }
    return self;
}

- (void)addSubViews
{
    self.backView = [[UIView alloc] init];
    self.backView.backgroundColor = [UIColor whiteColor];
    self.backView.layer.masksToBounds = YES;
    self.backView.layer.cornerRadius = 7 * kScale;
    [self.contentView addSubview:self.backView];
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.contentView.mas_left);
         make.top.equalTo(self.contentView.mas_top);
         make.right.equalTo(self.contentView.mas_right);
         make.bottom.equalTo(self.contentView.mas_bottom);
     }];

    UICollectionViewFlowLayout  *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 2 * kScale;
    layout.minimumInteritemSpacing = 12 * kScale;
    layout.itemSize = CGSizeMake(108 * kScale, 68 * kScale);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.collectionView registerClass:[WGQAlbumCollectionViewCell class] forCellWithReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([WGQAlbumCollectionViewCell class])]];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.contentView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.contentView.mas_left).offset(12 * kScale);
         make.top.equalTo(self.contentView.mas_top).offset(12 * kScale);
         make.right.equalTo(self.contentView.mas_right).offset(-12 * kScale);
         make.bottom.equalTo(self.contentView.mas_bottom).offset(-12 * kScale);
     }];
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]                                             initWithTarget:self                                             action:@selector(myHandleTableviewCellLongPressed:)];
    longPress.minimumPressDuration = 1.0;  //将长按手势添加到需要实现长按操作的视图里
    [self.collectionView addGestureRecognizer:longPress];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.collectionArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WGQAlbumCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([WGQAlbumCollectionViewCell class])] forIndexPath:indexPath];
    [cell setObject:self.collectionArray[indexPath.row]];
    return cell;
}

- (void)myHandleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint pointTouch = [gestureRecognizer locationInView:self.collectionView];
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        DLog(@"UIGestureRecognizerStateBegan");
        NSIndexPath * indexPath = [self.collectionView indexPathForItemAtPoint:pointTouch];
        if (indexPath == nil)
        {
            DLog(@"空");
        }
        else
        {
            DLog(@"Section = %ld,Row = %ld",(long)indexPath.section,(long)indexPath.row);
            self.indexPath = indexPath;
            [self showAlertView];
        }
    }
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged)
    {
        DLog(@"UIGestureRecognizerStateChanged");
        
    }
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
    {
        DLog(@"UIGestureRecognizerStateEnded");
    }
}

- (void)showAlertView
{
    NSArray * array = @[@"保存图片至本地",@"图片另存至相册"];
    WGQTransfersRecordsAlertView * alertView = [[WGQTransfersRecordsAlertView alloc] initWithFrame:CGRectMake(100 * kScale, (kScreenHeight - array.count * 40 * kScale)/2, 160 * kScale, array.count * 40 * kScale) andTitleArray:array];
    alertView.layer.masksToBounds = YES;
    alertView.layer.cornerRadius = 4 * kScale;
    [alertView show];
    
    //弹框数据的回调
    __weak __typeof(&*self)weakSelf = self;
    alertView.click_index_block = ^(NSInteger index)
    {
        switch (index)
        {
            case 0:
            {
                //图片保存至本地
                 [self dowlondImage];
            }
                break;
            case 1:
            {
                //图片另存至相册
                [weakSelf photoSaveToAlbumsWithImageUrl:@"图片已保存至相册"];
            }
                break;
            default:
                break;
        }
    };
}

- (void)dowlondImage
{
    WGQGrowUpLittleModel * model = self.collectionArray[self.indexPath.row];
    //下载当前图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 加载数据
        UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,model.ps_id]]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (image)
            {
                [self saveImageBtnActionWithImage:image];
            }
        });
    });
}

- (void)saveImageBtnActionWithImage:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (self.image_save_success_block)
    {
        self.image_save_success_block(@"图片已保存至本地");
    }
}

//图片另存至相册,发生网络请求，将图片存在当前账户下的某个相册
- (void)photoSaveToAlbumsWithImageUrl:(NSString *)string
{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
         request.URLString = @"http://www.armyant.com.cn:8082/Army/v1.1_photocopy/update?ids=111&ph_id=111";
         //         request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=user_child&status=1",Pick_up_baby,userinfo.ID];
         request.methodType = ZBMethodTypeGET;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             if (self.image_save_success_block)
             {
                 self.image_save_success_block(@"图片已保存至相册");
             }
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}

- (void)setObject:(id)object
{
    if ([object isKindOfClass:[NSArray class]])
    {
        self.collectionArray = [NSMutableArray arrayWithArray:object];
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make)
         {
             make.left.equalTo(self.contentView.mas_left).offset(12 * kScale);
             make.right.equalTo(self.contentView.mas_right).offset(-12 * kScale);
             if (self.collectionArray.count <= 0)
             {
                 self.backView.backgroundColor = FFColor(0xebebeb);
                 make.top.equalTo(self.contentView.mas_top);
                 make.height.priorityHigh().equalTo(@(0));
                 make.bottom.equalTo(self.contentView.mas_bottom).offset(-1);
             }
             else
             {
                 self.backView.backgroundColor = [UIColor whiteColor];
                 make.top.equalTo(self.contentView.mas_top).offset(12 * kScale);
                 make.height.priorityHigh().equalTo(@(ceil(self.collectionArray.count / 3.0) * 70 * kScale + 12 * kScale * floorf((self.collectionArray.count - 1) / 3)));
                 make.bottom.equalTo(self.contentView.mas_bottom).offset(-12 * kScale);
             }
         }];
        [self.collectionView reloadData];
    }
}

- (void)awakeFromNib
{
    [super awakeFromNib];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

@end
